#include "stockindialog.h"
#include "ui_stockindialog.h"


#include <QSqlQuery>
#include <QJsonArray>
#include <QJsonObject>
#include <QJsonDocument>
#include <QMessageBox>
#include <QSqlError>
StockInDialog::StockInDialog(QWidget *parent)
    : QDialog(parent)
    , ui(new Ui::StockInDialog)
    , model(new QStandardItemModel(this))
{
    ui->setupUi(this);

    setWindowTitle("创建入库单");
    //初始化数据
    initData();

    connect(ui->cmbReportId, QOverload<int>::of(&QComboBox::currentIndexChanged), this, &StockInDialog::onReportSelected);

}

StockInDialog::~StockInDialog()
{
    delete ui;
}

void StockInDialog::closeEvent(QCloseEvent *event)
{
    emit stockInDialogClosed();
    event->accept();
}

void StockInDialog::initData()
{
    //初始化验收单编号下拉框
    ui->cmbReportId->addItem("--请选择验收单--");
    QSqlQuery reportIdQuery("SELECT report_id, po_id, inspector FROM ReceivingReport WHERE inspection_result = '合格'");
    while (reportIdQuery.next())
    {
        ui->cmbReportId->addItem(reportIdQuery.value("report_id").toString(),
                                 QVariantList{reportIdQuery.value("po_id"),reportIdQuery.value("inspector")});
    }
    //初始化仓库下拉框
    QSqlQuery warehousequery("SELECT warehouse_id, warehouse_name FROM Warehouse");
    while (warehousequery.next())
    {
        ui->cmbWarehouse->addItem(warehousequery.value("warehouse_name").toString(), warehousequery.value("warehouse_id"));
    }

    ui->cmbSourceType->addItems({"采购入库", "调拨入库", "其他"});
    ui->cmbSourceType->setCurrentIndex(0);

    //设置表格模型
    model->setColumnCount(6);
    model->setHorizontalHeaderLabels({"产品ID", "产品名称", "规格", "单位", "入库数量", "存放位置"});
    ui->tableView->setModel(model);
    //隐藏产品ID列
    ui->tableView->setColumnHidden(0, true);

}

void StockInDialog::clearInfo()
{
    ui->lblPoId->setText(QString("采购订单编号:"));
    ui->lblInspector->setText(QString("验收员："));

    model->removeRows(0, model->rowCount());
}

void StockInDialog::on_buttonBox_accepted()
{
    onSubmit();
    emit stockInDialogClosed();
    accept();
}


void StockInDialog::on_buttonBox_rejected()
{
    emit stockInDialogClosed();
    reject();
}

void StockInDialog::onReportSelected(int index)
{
    if (index <=0)
    {
        clearInfo();
        return;
    }

    //获取验收单对应的采购订单号和验收明细
    QVariantList data = ui->cmbReportId->itemData(index).toList();
    int poId = data[0].toInt();
    QString inspector = data[1].toString();

    ui->lblPoId->setText(QString("采购订单编号：%1").arg(poId));
    ui->lblInspector->setText(QString("验收员：%1").arg(inspector));

    //清空模型
    model->removeRows(0, model->rowCount());

    // 加载产品明细
    QSqlQuery query;
    query.prepare(
        "SELECT Product.product_id, Product.name, Product.spec, Product.unit, PurchaseOrderDetail.quantity "
        "FROM PurchaseOrderDetail "
        "JOIN SupplierProduct ON PurchaseOrderDetail.supplier_product_id = SupplierProduct.supplier_product_id "
        "JOIN Product ON SupplierProduct.product_id = Product.product_id "
        "WHERE PurchaseOrderDetail.po_id = ?"
        );
    query.addBindValue(poId);
    if (!query.exec())
    {
        QMessageBox::warning(this, "错误", "加载产品明细失败: " + query.lastError().text());
        return;
    }

    while (query.next())
    {
        int row = model->rowCount();
        model->insertRow(row);
        // 产品ID（隐藏）
        QStandardItem *idItem = new QStandardItem(query.value("product_id").toString());
        model->setItem(row, 0, idItem);

        // 产品名称
        QStandardItem *nameItem = new QStandardItem(query.value("name").toString());
        nameItem->setEditable(false);
        model->setItem(row, 1, nameItem);

        // 规格
        QStandardItem *specItem = new QStandardItem(query.value("spec").toString());
        specItem->setEditable(false);
        model->setItem(row, 2, specItem);

        // 单位
        QStandardItem *unitItem = new QStandardItem(query.value("unit").toString());
        unitItem->setEditable(false);
        model->setItem(row, 3, unitItem);

        // 入库数量（默认等于采购数量，可编辑）
        QStandardItem *qtyItem = new QStandardItem(query.value("quantity").toString());
        model->setItem(row, 4, qtyItem);

        // 存放位置（可编辑）
        model->setItem(row, 5, new QStandardItem(""));
    }
    // 调整列宽
    ui->tableView->resizeColumnsToContents();
}

void StockInDialog::onSubmit()
{
    //获取当前验收单ID
    int reportId = ui->cmbReportId->currentText().toInt();
    int warehouseId = ui->cmbWarehouse->currentData().toInt();
    QString handler = ui->leHandler->text();
    QString sourceType = ui->cmbSourceType->currentText();

    if (handler.isEmpty())
    {
        QMessageBox::warning(this, "错误", "操作员不能为空");
        return;
    }

    //构建JSON数组
    QJsonArray details;
    for (int row = 0; row < model->rowCount(); row++)
    {
        int productId = model->item(row, 0)->text().toInt();
        int qtyIn = model->item(row, 4)->text().toInt();
        QString position = model->item(row, 5)->text();

        if (qtyIn <= 0)
        {
            QMessageBox::warning(this, "错误", QString("第%1行的入库数量必须大于0").arg(row+1));
            return;
        }

        if (position.isEmpty())
        {
            QMessageBox::warning(this, "错误", QString("第%1行的存放位置不能为空").arg(row+1));
            return;
        }
        if (model->rowCount() == 0)
        {
            QMessageBox::warning(this, "错误", "入库明细不能为空");
            return;
        }
        QJsonObject detail;
        detail["product_id"] = productId;
        detail["qty_in"] = qtyIn;
        detail["position"] = position;
        details.append(detail);
    }
    QJsonDocument doc(details);
    QString jsonString = doc.toJson(QJsonDocument::Compact);

    //调用存储过程
    QSqlQuery queryCall;
    queryCall.prepare("CALL CreateStockInRecord(?, ?, ?, ?, ?, @out_result)");
    queryCall.addBindValue(reportId);
    queryCall.addBindValue(warehouseId);
    queryCall.addBindValue(handler);
    queryCall.addBindValue(sourceType);
    queryCall.addBindValue(jsonString);

    if (!queryCall.exec())
    {
        QMessageBox::critical(this, "错误", "调用存储过程失败: " + queryCall.lastError().text());
        return;
    }

    // 获取输出参数
    queryCall.exec("SELECT @out_result");
    if (queryCall.next())
    {
        int result = queryCall.value(0).toInt();
        if (result == 1)
        {
            QMessageBox::information(this, "成功", "入库单创建成功");
        }
        else
        {
            QMessageBox::warning(this, "失败", "入库单创建失败");
        }
    }
    else
    {
        QMessageBox::critical(this, "错误", "无法获取存储过程结果");
    }

}

